import React, { PureComponent, useState } from 'react'
import { Card, Row, Col, Tooltip, Modal, Button, message } from 'antd';
import styles from './index.less';
import imgs from '@/assets/index'
import { getStudentSubject } from '@/services/studentPractice'
import { history } from 'umi';
import { UserOutlined, ClockCircleOutlined } from '@ant-design/icons';
import { settingShow } from '@/services/setting'
import { checkExamineIdNumber } from '@/services/peoples'
import { changePlate } from '@/services/login'
import { studentAnalyze } from '@/services/studentAnalyze'
import { isTzsbpx, isAnquanpx, isLianxi, hasIsSw, learnTime, hasProgressFunc, isOnlyBinhai, isCeshi, isJuan } from '@/utils/utils'
import moment from 'moment';
export default class MainTop extends PureComponent<any, any> {
    constructor(props: any) {
        super(props)
        const plate = JSON.parse(localStorage.getItem('userinfo') || "{}").is_sw * 1
        const month = new Date().getMonth() + 1;

        this.state = {
            integral: 0,
            created_ats: '',
            default_integral: 0,
            teachVisible: false,
            hasTwo: 2,
            plate,
            percent: 0,
            subject: '',
            currentTime: month < 7,
            isModalVisible: false,
            setIsModalVisible: false,
        }
    }
    goTo = (link: string) => () => {
        history.push(link)
    }
    showVideo = () => {
        this.setState({
            teachVisible: true
        })
    }
    goDocument = () => {
        history.push('/document')
    }
    handleOk = () => {
        this.setState({
            setIsModalVisible: false
        })
    };
    handleCancel = () => {
        this.setState({
            teachVisible: true
        })
    };

    getAnalyze = (currentTime) => {
        const uid = localStorage.getItem('id') || '';
        const subject = this.state.subject.split(',')
        studentAnalyze({ uid, subject: subject[0], hasTime: currentTime ? 1 : 2 }).then(res => {
            const percent = (res.zx[3].value / 40).toFixed(2)
            localStorage.setItem('percent', percent)
            this.setState({
                percent: Number(percent)
            })
        })
    }
    componentDidMount() {
        const uid = localStorage.getItem('id') || '';
        const id_number = localStorage.getItem('id_number') || '';
        getStudentSubject({ uid }).then(res => {
            if (!res) return;
            this.setState({
                integral: res.integral,
                created_ats: res.created_ats,
                subject: res.subject
            })
            if (hasProgressFunc()) {
                const { currentTime } = this.state;
                this.getAnalyze(currentTime)
            }
        })
        settingShow().then(res => {
            this.setState({
                default_integral: res.default_integral
            })
        })

        if (hasIsSw()) {
            checkExamineIdNumber({ id_number }).then(res => {
                this.setState({
                    hasTwo: res.status
                })
                localStorage.setItem('hasTwo', res.status)
            })
        }
    }
    changePlate = (is_sw: number) => () => {
        const { plate } = this.state;
        if (is_sw === plate) return;
        const id_number = localStorage.getItem('id_number') || '';
        Modal.confirm({
            title: '提示',
            content: `确定切换${is_sw === 1 ? '特种作业' : '特种设备'}平台？`,
            onOk: () => {
                changePlate({ id_number, is_sw }).then(response => {
                    if (response.status === 2) return message.error('您没有权限进入此平台，请联系管理员开通')
                    localStorage.setItem('name', response.name);
                    localStorage.setItem('id_number', response.id_number);
                    localStorage.setItem('type', response.type);
                    localStorage.setItem('subjects', response.subjects);
                    localStorage.setItem('id', response.id);
                    localStorage.setItem('userinfo', JSON.stringify(response));
                    localStorage.setItem('timestamp', response.timestamp)
                    location.reload()
                })
            }
        })
    }
    changeProgressData = (num: number) => () => {
        const month = new Date().getMonth() + 1;
        const { currentTime } = this.state;
        if ((currentTime && num === 1) || (!currentTime && num === 2)) return;
        if (month < 7 && num === 2) {
            return Modal.info({ title: '提示', content: '培训时间还未到下半年，6月30号之后可以报名下半年培训' })
        }
        this.getAnalyze(num === 1 ? true : false)
        if (num === 1) {
            this.setState({
                currentTime: true
            })
        } else {
            this.setState({
                currentTime: false
            })
        }
    }
    
    render() {
        const { integral, created_ats, default_integral, teachVisible, hasTwo, plate, percent, currentTime,subject } = this.state;
        const userinfo = JSON.parse(localStorage.getItem('userinfo') || '{}');
        const subjects = userinfo.subjects.substr(0, userinfo.subjects.length - 1).replace(/-/g, '/');
        const logintime = moment(Number(localStorage.getItem('logintime'))).format('YYYY-MM-DD HH:mm:ss');
        // const hasProgress = isCustome() && (subject * 1 === 144 || subject * 1 === 145)
        const list = !isTzsbpx() ? [
            {
                link: '/train',
                src: imgs.book,
                title: '培训学习',
                span: 8
            },
            {
                link: '/select',
                src: imgs.exam,
                title: isJuan() ? '正式考试' : '模拟考试',
                span: 8,
                style: {},
                
            },
            {
                link: '/practice',
                src: imgs.practice,
                title: '专项练习',
                span: 8
            },



        ] : [
            {
                link: '/practice',
                src: imgs.practice,
                title: '考题练习',
                span: 12
            },
            {
                link: isLianxi() ? `/select` : `/exam/${userinfo.subject}/2`,
                src: imgs.exam,
                title: '模拟考试',
                span: 12
            },
        ]
        if (isAnquanpx()) {
            list.reverse()
        }
        if (isOnlyBinhai()) {
            list[1] = {
                link: `/exam/${userinfo.subject}/2`,
                src: imgs.exam2,
                title: '模拟考试(优先练习)',
                span: 8,
                style: { color: "#fda63f" }
            }
        }

        const countPercent = Number((percent * (100 / learnTime())).toFixed(2))
        return (
            <React.Fragment>
                <Modal width={900} visible={teachVisible} footer={null} onCancel={() => this.setState({ teachVisible: false })}>
                    {teachVisible && <video controls autoPlay style={{ width: '100%', height: 500 }} src={"https://www.shejiyuan.com/Public/images/exam_teach.m4v"}></video>}
                </Modal>
                <Card style={{ marginBottom: 25 }} bordered={false}>
                    <p className={styles['info-title']}> <img src={imgs.info} alt=" " />个人信息</p>
                    <div className={styles['info-content']}>
                        <Row>
                            <Col>
                                <img src={imgs.user} className={styles['info-icon']} alt=" " />
                            </Col>
                            <Col span={8} style={{ textIndent: 20 }}>
                                {
                                    (hasProgressFunc()) && <div onClick={() => history.push('/learnAnalyze')} style={{ cursor: 'pointer', position: 'absolute', left: 0, top: '-28px', width: 900, justifyContent: 'left', display: 'flex' }}>
                                        <b style={{ fontSize: 15, color: "#1890ff", whiteSpace: 'nowrap' }}>学习时长:{percent > 100 ? 100 : percent}学时</b>
                                        <div className={styles['progress']}>
                                            <div className={styles['progress-inner']}>
                                                <p className={styles['progress-text']}> 学习进度:{Number((percent * (100 / learnTime())).toFixed(1))}%</p>
                                                <div style={{ width: (countPercent > 100 ? 100 : countPercent) + '%' }} className={styles['progress-bg']}></div>
                                            </div>

                                        </div>
                                        <b style={{ fontSize: 15, color: "#fda63f", whiteSpace: 'nowrap' }}>目标学时：{learnTime()}学时</b>
                                        {
                                            (hasProgressFunc() && percent >= learnTime()) && <b style={{ whiteSpace: 'nowrap' }}>
                                                您的线上培训学习时长已达到{learnTime()}学时，可以进行考试取证</b>
                                        }
                                    </div>
                                }

                                <p className={styles['info-name']}><a>{userinfo.name || '欢迎进入在线培训学习系统'}</a>
                                    {
                                        hasTwo === 1 && <React.Fragment>
                                            <span style={{ background: plate === 2 ? '#fda63f' : '#0096ff' }} className={styles['train-tsbutton']} onClick={this.changePlate(2)}>特种设备培训</span>
                                            <span style={{ background: plate === 1 ? '#fda63f' : '#0096ff' }} className={styles['train-tzbutton']} onClick={this.changePlate(1)}>特种作业培训</span>
                                        </React.Fragment>
                                    }

                                </p>
                                <Tooltip title={subjects}><p className={styles['info-item']}>准考证号：{userinfo.id_number}</p></Tooltip>
                                <Tooltip title={subjects}><p className={styles['info-item']} >培训科目：{subjects}</p></Tooltip>
                            </Col>
                            <Col span={5}>
                                <div className={styles['info-content-item']}>
                                    {
                                        default_integral !== 0 && <p className={styles['info-item']}>积分：{integral}</p>
                                    }
                                    <Tooltip title={created_ats}><p className={styles['info-item']} >开通时间：{created_ats}</p></Tooltip>
                                </div>
                            </Col>
                            <Col span={6}>
                                {
                                    isOnlyBinhai() && <div className={styles['time-buttons']}>
                                        <Button onClick={this.changeProgressData(1)} style={{ marginRight: 10, background: currentTime ? "#fda63f" : "", borderColor: currentTime ? "#fda63f" : "" }} type="primary">上半年培训</Button>
                                        <Button onClick={this.changeProgressData(2)} style={{ background: !currentTime ? "#fda63f" : "", borderColor: !currentTime ? "#fda63f" : "" }} type="primary">下半年培训</Button>
                                    </div>
                                }
                                <div className={styles['info-content-item']}>
                                    <Tooltip title={logintime}><p className={styles['info-item']}><ClockCircleOutlined />最近登录时间： {logintime}</p></Tooltip>
                                    <p className={styles['info-item']} >
                                        <span onClick={() => history.push('/info')}><UserOutlined /> 个人信息修改</span>
                                         &nbsp;&nbsp;&nbsp;
                                        {/* <span onClick={this.showVideo}> <FileSearchOutlined /> 操作指南</span> */}
                                        <Button type="primary" style={{ backgroundColor: "#fda63f", borderColor: "#fda63f" }} onClick={this.goDocument}>学员公告</Button>

                                    </p>
                                </div>
                            </Col>

                        </Row>
                    </div>
                </Card>
                <Row>
                    {
                        list.map(item => {
                            return <Col span={item.span} onClick={
                                this.goTo(item.link)
                              
                            } key={item.title}>
                                <Card.Grid className={styles['main-top-cards']} style={{ width: '100%', backgroundColor: "#fff" }}>
                                    <img src={item.src} alt=" " />
                                    <p style={item.style}>{item.title}</p>
                                </Card.Grid>
                            </Col>
                        })
                    }
                </Row>
            </React.Fragment>
        )
    }
}
